package com.lucenly.card.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;

import com.lucenly.card.R;
import com.lucenly.card.app.MyApplication;
import com.lucenly.card.constants.Constants;
import com.lucenly.card.constants.UrlDefend;
import com.lucenly.card.event.StringMsgEvent;
import com.siberiadante.toastutils.ToastUtil;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.vise.xsnow.dialog.PromptDialog;
import com.vise.xsnow.event.BusManager;
import com.vise.xsnow.http.ViseHttp;
import com.vise.xsnow.http.callback.ACallback;
import com.vise.xsnow.http.config.GlobalData;
import com.vise.xsnow.utls.SharedPreferencesUtil;

import org.json.JSONException;
import org.json.JSONObject;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler{
    PromptDialog dialog;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wx);
        dialog = new PromptDialog(this);
        MyApplication.getInstance().getApi().handleIntent(getIntent(),this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        MyApplication.getInstance().getApi().handleIntent(intent, this);//必须调用此句话
    }
    @Override
    public void onReq(BaseReq baseReq) {
        if(baseReq.transaction!=null&&baseReq.transaction.equals("share")){

        }else{
            dialog.showLoading("正在登录中...");
        }
    }

    @Override
    public void onResp(BaseResp baseResp) {
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                //发送成功
                if(baseResp.transaction!=null&&baseResp.transaction.equals("share")){
//                    Toast.makeText(this, "分享成功!", Toast.LENGTH_SHORT).show();
//                    ToastUtil.showSingletonShort("分享成功!");dialog.dismiss();
                    finish();
                }else{
                    dialog.showLoading("正在登录中...");
                    SendAuth.Resp sendResp = (SendAuth.Resp) baseResp;
                    if (sendResp != null) {
                        String code = sendResp.code;
                        getAccess_token(code);
                    }
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                //发送取消
                String msg = "";
                if(baseResp.transaction!=null&&baseResp.transaction.equals("share")){
                    msg = "分享";
                }else{
                    msg = "登录";
                }ToastUtil.showSingletonShort(msg+"取消了");
//                Toast.makeText(this, msg+"取消了", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
                finish();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                //发送被拒绝
                break;
            default:
                //发送返回
                finish();
                break;
        }
    }
    /**
     * 获取openid accessToken值用于后期操作
     * @param code 请求码
     */
    private void getAccess_token(final String code) {
        String path = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                + Constants.APP_ID
                + "&secret="
                + Constants.AppSECRET
                + "&code="
                + code
                + "&grant_type=authorization_code";
        ViseHttp.GET(path)
                .request(new ACallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(result);
                            String openid = jsonObject.getString("openid").toString().trim();
                            String access_token = jsonObject.getString("access_token").toString().trim();
                            getUserMesg(access_token, openid);
                        } catch (JSONException e) {
                            e.printStackTrace();
                            dialog.dismiss();
                            finish();
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
//                        Toast.makeText(WXEntryActivity.this,"授权失败",Toast.LENGTH_SHORT).show();
                        ToastUtil.showSingletonShort("授权失败");dialog.dismiss();
                        finish();
                    }
                });
    }
    /**
     * 获取微信的个人信息
     * @param access_token
     * @param openid
     */
    private void getUserMesg(final String access_token, final String openid) {
        String path = "https://api.weixin.qq.com/sns/userinfo?access_token="
                + access_token
                + "&openid="
                + openid;
        ViseHttp.GET(path)
                .request(new ACallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        Login(data);
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
//                        Toast.makeText(WXEntryActivity.this,"登录失败",Toast.LENGTH_SHORT).show();
                        ToastUtil.showSingletonShort("登录失败");dialog.dismiss();
                        finish();
                    }
                });
    }

    private void Login(String data) {
        try {
            JSONObject jsonObject = new JSONObject(data);
            String openid = jsonObject.getString("openid");
            String unionid = jsonObject.getString("unionid");
            String nickname = jsonObject.getString("nickname");
            String avatar = jsonObject.getString("headimgurl");
            ViseHttp.POST(UrlDefend.LOGIN_WX)
                    .addParam("openid",openid)
                    .addParam("unionid",unionid)
                    .addParam("nickname",nickname)
                    .addParam("avatar",avatar)
//                    .addParam("wxData",data)
                    .request(new ACallback<String>() {
                        @Override
                        public void onSuccess(String data) {
                            dialog.dismiss();
                            try {
                                JSONObject jsonObject = new JSONObject(data);
                                String token = jsonObject.getString("token");
                                GlobalData.token = token;
                                SharedPreferencesUtil.getInstance().putString("Token",token);
                                BusManager.getBus().post(new StringMsgEvent("login"));ToastUtil.showSingletonShort("登录成功");
//                                Toast.makeText(WXEntryActivity.this, "登录成功!", Toast.LENGTH_SHORT).show();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            finish();
                        }

                        @Override
                        public void onFail(int errCode, String errMsg) {
                            dialog.dismiss();
                            finish();
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
